package com.example.spinnertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import static com.example.spinnertest.R.id.textView;

public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        //定义数据源
        String [] cities = {"北京", "上海", "大连", "天津"};
        //定义适配器
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cities);
        //定义Spinner下拉按钮样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //Spinner与Adapter绑定
        spinner.setAdapter(adapter);
        //Spinner点击条目事件
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tv.setText("您选择的是" + parent.getItemAtPosition(position).toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //不操作
            }
        });
    }

    private void init(){
        tv = (TextView) findViewById(textView);
        spinner = (Spinner) findViewById(R.id.spinner);
    }
}
